package com.learn.eduuserboot.controller;


import com.learn.eduapi.entity.ResponseDTO;
import com.learn.eduapi.entity.user.User;
import com.learn.eduuserboot.service.UserService;
import com.learn.eduuserboot.until.*;
import com.learn.eduuserboot.until.minio.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户微服务80
 */
@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired JwtUtil jwtUtil;
    @Autowired
    private OosUtil oosUtil;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * 获取用户列表
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("getUserList")
    public ResponseDTO<List<User>> getUserList(@RequestParam("find")String find,
                                               @RequestParam("page")Integer page,
                                               @RequestParam("size")Integer size){
        ResponseDTO<List<User>> responseDTO = new ResponseDTO<>();
        List<User> userList = userService.getUserList(find,(page-1)*size,size);
        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).getStatus().equals("ENABLE")){
                userList.get(i).setStatusId(0);
            }else {
                userList.get(i).setStatusId(1);
            }
        }
            responseDTO.setContent(userList);
            responseDTO.setState(userService.getUserList(find,0,0).size());
            responseDTO.setMessage("获取用户列表成功");
        return responseDTO;
    }

    @GetMapping("login")
    public ResponseDTO<User> login(@RequestParam("phone") String phone, @RequestParam("password") String pwd)throws Exception {
        System.out.println("phone = " + phone);
        System.out.println("pwd = " + pwd);
        ResponseDTO<User> responseDTO = new ResponseDTO<>();
        User user = userService.selectByPhone(phone);
        if (user != null) {
            //获取盐
            String salt = user.getSalt();
            String password = salt + pwd;
            String md5 = MD5Util.md5Encode(password);
            if (user.getPassword().equals(md5) != false) {
                if (user.getStatus().equals("ENABLE")!=true){
                    responseDTO.setState(500);
                    responseDTO.setMessage("该账号已被停用");
                    return responseDTO;
                }else if (user.getIsDel()!=0) {
                    responseDTO.setState(500);
                    responseDTO.setMessage("该账号已被删除");
                    return responseDTO;
                }else {
                    responseDTO.setContent(user);
                    responseDTO.setState(200);
                    responseDTO.setMessage("登陆成功");
                    return responseDTO;
                }
            } else {
                //密码错误
                responseDTO.setState(500);
                responseDTO.setMessage("手机号或者密码错误！");
                return responseDTO;
            }
        } else {
            if (ValidateUtils.isMobile(phone) != true) {
                //手机号格式不对
                responseDTO.setState(500);
                responseDTO.setMessage("手机号格式不对!");
                return responseDTO;
            } else {
                //手机号不存在，直接注册
                User u = new User();
                u.setName("学习新人"+phone);
                u.setPortrait("https://2oa-file.oss-cn-beijing.aliyuncs.com/t/2021-11-29/050d7131849e4795a5eab190353fcac3-Snipaste_2021-11-15_09-13-07.png");
                u.setPhone(phone);
                u.setStatus("ENABLE");
                u.setIsDel(0);
                u.setWeixin(0);

                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = sdf.format(date);

                u.setCreateTime(dateString);
                u.setUpdateTime(dateString);
                // 获取用户密码
// 获取盐值
            String salt = RandomCharecters.getRandomString(4);
// 盐值加上密码
            String password = salt + pwd;
// 对加上盐值的密码进行加密
            String md5 = MD5Util.md5Encode(password);
// 把加密后的密码存到user对象中
            u.setPassword(md5);
// 把盐值存入user对象中
                u.setSalt(salt);
                int i = userService.insertUser(u);
                responseDTO.setContent(userService.selectByPhone(phone));
                responseDTO.setState(200);
                responseDTO.setMessage("登陆成功");
                return responseDTO;
            }
        }


    }

    /**
     * 修改昵称和头像
     * @param id
     * @param name
     * @param portrait
     * @return
     */
    @GetMapping("updateUser")
    public ResponseDTO<User> updateUser(@RequestParam("userid")Long id,@RequestParam("newName")String name,@RequestParam("fileId") String portrait){
        User user = new User();
        user.setId(id);
        user.setName(name);

        if (portrait.length()>10){
            System.out.println("portrait = " + portrait);
            user.setPortrait(portrait);
        }

        Date date = new Date();
        //Date类型转String  //可指定任意的返回格式  yyyy
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date);
        user.setUpdateTime(dateString);

        int i = userService.updateUser(user);
        System.out.println("i = " + i);
        ResponseDTO<User> responseDTO = new ResponseDTO<>();
        responseDTO.setContent(user);
        responseDTO.setState(200);
        responseDTO.setMessage("更新信息成功");

        return responseDTO;
    }

    /**
     * OSS上传头像
     * @param file
     * @return
     */
    @PostMapping("upload")
    public String uploadHead(@RequestParam("file") MultipartFile file){

        String shuffix = oosUtil.getPicSuffix(file.getOriginalFilename());
        long size = file.getSize();
        String type = file.getContentType();
        String fileId = oosUtil.getImgUrl(oosUtil.uploadImg2Oss(file));
        return fileId;
    }

    /**
     * MinIO上传头像
     * @param file
     * @return
     */
    @PostMapping("uploadMinio")
    public String uploadHeadMINIO(@RequestParam("file") MultipartFile file){

        if (file.isEmpty() || file.getSize() == 0) {
            return "文件为空";
        }
        try {
            if (!minioUtil.bucketExists("javakf")) {
                minioUtil.makeBucket("javakf");
            }

            String fileName = file.getOriginalFilename();
            String newName = "image/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));

            InputStream inputStream = file.getInputStream();
            minioUtil.putObject("javakf", newName, inputStream);
            inputStream.close();
            String url = minioUtil.getObjectUrl("javakf", newName);
            System.out.println("url = " + url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }



    @GetMapping("Password")
    public ResponseDTO<User>  Password(@RequestParam("userid")Long id,@RequestParam("oldPwd") String oldPwd)throws Exception{
        ResponseDTO<User> responseDTO = new ResponseDTO<>();
        User user = userService.selectById(id);
        //获取盐
        String salt = user.getSalt();
        String pwd = salt + oldPwd;
        String md5 = MD5Util.md5Encode(pwd);
        if (md5.equals(user.getPassword())){
            responseDTO.setState(200);
        }else {
            responseDTO.setState(500);
        }
        return responseDTO;

    }
        /**
         * 修改密码
         * @param id
         * @param password
         * @return
         * @throws Exception
         */
    @GetMapping("updatePassword")
    public User  updatePassword(@RequestParam("userid")Long id,@RequestParam("newPwd") String password)throws Exception{
        User user = userService.selectById(id);
        //获取盐
        String salt = user.getSalt();
        String pwd = salt + password;
        String md5 = MD5Util.md5Encode(pwd);
        User u = new User();
        u.setId(id);
        u.setPassword(md5);

        Date date = new Date();
        //Date类型转String  //可指定任意的返回格式  yyyy
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date);
        u.setUpdateTime(dateString);

        int i = userService.updateUser(u);
        return u;
    }

}
